// import Vue from 'vue';
// import VueAxios from 'vue-axios'
import axios from 'axios';
// import qs from 'qs';

// Vue.use(VueAxios, axios);

// var serverUrl = 'http://localhost:3000';
var serverUrl = 'http://182.150.13.196:3456';

export function range (_min, _max) {
  if (_max === undefined) {
    _max = _min;
    _min = 0;
  }
  var rt = [];
  for (var i = _min; i < _max; i++) rt.push(i);
  return rt;
}

export function memset (count, value) {
  return range(count).map(function () { return value; });
}

export function flat (ary) {
  return ary.reduce(function (a, b) {
    return (b.constructor === Array) ? a.concat(flat(b)) : a.concat(b);
  }, []);
}

export function setCookie (name, value, hour) {
  hour = hour || 2;
  let exp = new Date();
  exp.setTime(exp.getTime() + hour * 3600 * 1000);
  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toUTCString();
}

export function getCookie (name) {
  var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null;
}

export function checkLogin (name) {
  let user = getCookie('username');
  if (user) return user;
  window.location.href = 'login.html';
  return false;
}

export function getParameterByName (name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

export function dateFormat (dt) {
  return dt.replace('T', ' ').substr(0, 16);
}

export function ajaxData (key, data, _callbackS, _callbackE, _callbackC) {
  let cbkf = (parseInt(Math.random() * 1000) + 1000).toString();
  data['session'] = getCookie('session');
  data['username'] = getCookie('username');
  $.ajax({
    type: 'GET',
    url: serverUrl + '/' + key + '/',
    data: data,
    dataType: 'jsonp',
    jsonpCallback: 'call1back' + cbkf + 'a',
    crossDomain: true,
    success: function (data) {
      if (_callbackS) _callbackS(data);
      if (data.error !== undefined) {
        if (data.error && data.errNum === 1) {
          // hideLoading();
          alert('当前用户权限不够，请联系管理员！');
        }
      }
    },
    error: function (data) {
      if (_callbackE)_callbackE(data);
      alert('error');
    },
    complete: function (data) {
      if (_callbackC) _callbackC(data);
    }
  });
}

export function postData (key, data, _callbackS, _callbackE) {
  data['username'] = getCookie('username');
  // let dt = qs.stringify(data, { indices: true });
  axios.post('/api/' + key, data)
    .then(function (rst) {
      if (_callbackS)_callbackS(rst);
    })
    .catch(function (rst) {
      if (_callbackE) _callbackE(rst);
    });
}
